//
//  MyEvaluateViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/11.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "EvaluateSectionHeaderView.h"
#import "EvaluateSectionFooterView.h"
#import "MyEvaCell.h"

#import "PostDetailViewController.h"
#import "TopicDetailViewController.h"
#import "QADetailViewController.h"

#import "MyEvaluateViewController.h"

@interface MyEvaluateViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview; 

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) NSMutableArray <CommunityInteractionModel *>*dataArray;

@end

@implementation MyEvaluateViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self refreshParam];
    [self request_evaList];
    [self initView];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)initView {
    
    self.title = @"我的评论";
    
    [self.view addSubview:self.tableview];
    
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.tableview reloadData];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [EvaluateSectionHeaderView calculateHWithModel:self.dataArray[section]];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    EvaluateSectionHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"EvaluateSectionHeaderView" owner:nil options:nil].firstObject;
    
    [sectionHeader fillWithModel:self.dataArray[section]];
    
    WEAKSELF
    sectionHeader.EvaluateDeleteBlock = ^{
        
        [TT_Alert alert:@"是否确定删除该评论" cancleBtnTitle:@"取消" cancleAction:^{
            
        } doneBtnTitle:@"确认" doneAction:^{
           
            [weakSelf request_deleteWithIndex:section];
        }];
        
    };
    
    return sectionHeader;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    EvaluateSectionFooterView*sectionFooter = [[NSBundle mainBundle] loadNibNamed:@"EvaluateSectionFooterView" owner:nil options:nil].firstObject;
    
    [sectionFooter fillWithModel:self.dataArray[section] type:EvaluateSectionFooter_myEva];
    
    
    
    return sectionFooter;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MyEvaCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyEvaCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillWithModel:self.dataArray[indexPath.section]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //类型（1：谈婚，2：论嫁，3：问答）必传
    switch (self.dataArray[indexPath.section].type) {
        case 1:{
            
            PostDetailViewController *vc = [[PostDetailViewController alloc] init];
            vc.pid = self.dataArray[indexPath.section].pid;
            [self.navigationController pushViewController:vc animated:YES];
        } break;
        case 2:{
            
            TopicDetailViewController *vc = [[TopicDetailViewController alloc] init];
            vc.pid = self.dataArray[indexPath.section].pid;
            [self.navigationController pushViewController:vc animated:YES];
        } break;
        case 3:{
            
            QADetailViewController *vc = [[QADetailViewController alloc] init];
            vc.mqId = self.dataArray[indexPath.section].pid;
            [self.navigationController pushViewController:vc animated:YES];
            
        } break;
        default:
            break;
    }
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
                
        [_tableview registerNib:[UINib nibWithNibName:@"MyEvaCell" bundle:nil] forCellReuseIdentifier:@"MyEvaCellID"];

        [self.view addSubview:_tableview];
        
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.bottom.mas_equalTo(0);
        }];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_evaList];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_evaList];
        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}


- (void)request_evaList {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    [t setValue:@"2" forKey:@"isDel"];
//    [t setValue:@"2" forKey:@"type"];
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [t setValue:@"1" forKey:@"mold"];
    
    [t setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_MyCommunityHD];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];

        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                    
                        if (weakSelf.pageNum == 1) {
                            self.dataArray = @[].mutableCopy;
                            
                            if (list.count == 0) {
                                [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_EmptyView btnTitle:@"" didPressButton:^{
                                }];
                            }
                        }
                        
                        for (NSDictionary *dic in list) {
                            
                            CommunityInteractionModel *model = [CommunityInteractionModel modelWithDictionary:dic];
                            [weakSelf.dataArray addObject:model];
                        }
                        
                        [weakSelf.tableview reloadData];
                    }
                }
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}


- (void)request_deleteWithIndex:(NSInteger)index {
        
    CommunityInteractionModel *model = self.dataArray[index];
    NSMutableDictionary *dic = @{}.mutableCopy;
        
    if ([model.level isEqualToString:@"1"]) {
        [dic setValue:model.pid forKey:@"baseId"];
    }
    
    if ([model.level isEqualToString:@"2"]) {
        [dic setValue:model.cpId forKey:@"baseId"];
    }
    
    if ([model.level isEqualToString:@"3"]) {
        [dic setValue:model.cspId forKey:@"baseId"];
    }
    
    if ([model.level isEqualToString:@"4"]) {
        [dic setValue:model.cspnId forKey:@"baseId"];
    }
    
    [dic setValue:model.interId forKey:@"otherId"];

    [dic setValue:model.level forKey:@"level"];
    [dic setValue:model.source forKey:@"source"];
    [dic setValue:model.userId forKey:@"userId"];
    

    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [dic setValue:@"3" forKey:@"mold"];

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@(model.type) forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                [weakSelf refreshParam];
                [weakSelf request_evaList];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

@end
